package com.irdstudio.efp.esb.service.facade;

import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.nls.service.facade.NlsQueueSoltComnService;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * 需求编号:2019D0910
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/8/19
 * 功能描述:
 * 修改日期:2019/8/19
 * 修改描述:
 */
public class EsbInvokeWrapper {
    // 方法
    private Method method;
    // 包装service
    private Object service;
    // 包装参数
    private Object parameter;
    // 告警
    private NlsQueueSoltComnService nlsQueueSoltComnService;

    public EsbInvokeWrapper(Object service, Object parameter, NlsQueueSoltComnService nlsQueueSoltComnService) {
        this.service = service;
        this.parameter = parameter;
        this.nlsQueueSoltComnService = nlsQueueSoltComnService;
    }

    public Object invoke3Threes() throws ESBException, InterruptedException {
        // 获取需要调用的方法
        Method[] declaredMethods = service.getClass().getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            String typeName = declaredMethod.getReturnType().getTypeName();
            if (typeName.contains("com.irdstudio.efp.esb.service.bo.resp")) {
                this.method = declaredMethod;
            }
        }
        if (this.method == null){
            throw new ESBException(method.getName()+" 方法调用失败,获取的方法为空!!!");
        }
        int count = 0;
        Object object = null;
        while (count <= 3){
            method.setAccessible(true);
            try {
                object = method.invoke(service, parameter);
                break;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                if (count == 3){
                    Throwable cause = e.getCause();
                    String message = cause.getMessage();
                    nlsQueueSoltComnService.alarmNotice(EsbBizEnums.AlarmObjectName.OCM_REAL_TIME.getValue(), EsbBizEnums.AlarmLvl.SERIOUS.getValue(), message);
                    throw new ESBException(EsbRetCodeStandard.SJCLYC.getValue(),message);
                }
                Thread.sleep(5000);
            }
            count++;
        }
        return object;
    }
}
